package com.example.chat03.service;

import com.example.chat03.model.StompAuthenticatedUser;
import com.example.chat03.model.WebSocketMsg;
import com.example.chat03.model.WebSocketMsgDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Service;

@Service
public class ChatService {
    private static final Logger logger = LoggerFactory.getLogger(ChatService.class);

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    public boolean sendMsg(String msg) {
        logger.info("msg:{}",msg);
        try {
            WebSocketMsgDTO webSocketMsgDTO = new ObjectMapper().readValue(msg, WebSocketMsgDTO.class);

            String content = String.format("私聊（自己发送他人接受）消息回复：来自[%s]的私聊消息：%s", webSocketMsgDTO.getName(), webSocketMsgDTO.getContent());
            simpMessagingTemplate.convertAndSendToUser(webSocketMsgDTO.getTo(),"/topic/chat-private2", WebSocketMsg.builder().content(content).build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
